package com.cjjd.c.feature.home.chekin.self_select;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;

import com.cjjd.c.EventBusKeys;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.ActionBarActivity;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.ListResult;
import com.cjjd.c.bean.OrderBean;
import com.cjjd.c.bean.SelectHomeItemBean;
import com.cjjd.c.feature.home.chekin.confirm_order.ConfirmOrderActivity;
import com.cjjd.c.feature.home.chekin.pay.PayPledgeActivity;
import com.cjjd.c.feature.home.chekin.select_people.SelectPeopleActivity;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/9/24.
 */

public class SelfSelectHomeActivity extends ActionBarActivity {


    @Bind(R.id.gridview)
    GridView gridview;
    @Bind(R.id.btn_next)
    Button btnNext;

    private String orderMainUuid;
    private String orderDetailUuid;
    private int unSelectNum = -1;
    private int selectNum = -1;
    private ArrayList<SelectHomeItemBean> datalist;
    private SelfSelectHomeAdapter selectHomeAdapter;

    @Override
    public Object getTitleString() {
        return "自主选房";
    }

    @Override
    public int getContentView() {
        return R.layout.fragment_self_select_home;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        orderMainUuid = getIntent().getStringExtra("mainUuid");


        LogUtil.e("xyd", "mainUuid  = " + orderMainUuid);
        orderDetailUuid = getIntent().getStringExtra("detailUuid");
        LogUtil.e("xyd", "mainUuid  = " + orderDetailUuid);
        initView();
        //toChooseRoom();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initRightButton(Button rightButton) {
        super.initRightButton(rightButton);
        //TODO dada add暂时屏蔽
        rightButton.setVisibility(View.VISIBLE);
        rightButton.setText("批量选房");
    }

    @Override
    public void onRightButtonClick() {
        super.onRightButtonClick();
        // TODO: 2017/9/24
        if (unSelectNum < 1) {
            ToastUtil.showToast("无房可选");
            return;
        }

        // 待选房间的 uuid
        ArrayList<String> orderDetailUuidslist = new ArrayList<>();
        for (SelectHomeItemBean itemBean : datalist) {
            if ("0".equals(itemBean.isChooseRoom)) {
                orderDetailUuidslist.add(itemBean.uuid);
            }
        }

        Intent intent = new Intent(mContext, SelectPeopleActivity.class);
        intent.putExtra("select_style", SelectPeopleActivity.SELECT_MULTI);
        intent.putExtra("unSelectNum", unSelectNum);
        intent.putExtra("orderMainUuid", orderMainUuid);
        intent.putExtra("orderDetailUuid", orderDetailUuid);
        intent.putStringArrayListExtra("orderDetailUuidslist", orderDetailUuidslist);
        mContext.startActivity(intent);
    }


    @Override
    public void onResume() {
        super.onResume();
        toChooseRoom();
    }

    private void toChooseRoom() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("orderUuid", orderMainUuid);                 // 预订单主表uuid
        h1.put("orderDetailUuid", orderDetailUuid);         // 预订单明细uuid

        Call<HttpResult<ListResult<SelectHomeItemBean>>> call = service.toChooseRoom(JsonUtils.convertParam("toChooseRoom", h1));
        call.enqueue(new CallbackImpl<ListResult<SelectHomeItemBean>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<SelectHomeItemBean>>> call, Response<HttpResult<ListResult<SelectHomeItemBean>>> response) {

                if (datalist.size() > 0) {
                    datalist.clear();
                }
                datalist.addAll(response.body().getData().dataList);

                // 计算有多少间未选房
                unSelectNum = 0;
                // 有多少件已经选房
                selectNum = 0;

                for (SelectHomeItemBean itemBean : datalist) {
                    if ("0".equals(itemBean.isChooseRoom)) unSelectNum++;
                    if ("1".equals(itemBean.isChooseRoom)) selectNum++;
                }

                selectHomeAdapter.notifyDataSetChanged();

            }
        });
    }

    private void initView() {
        selectHomeAdapter = new SelfSelectHomeAdapter(mContext);
        datalist = new ArrayList<>();
        selectHomeAdapter.setData(datalist);

        gridview.setAdapter(selectHomeAdapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // postion 从 0 开始
                if ("0".equals(datalist.get(position).isChooseRoom)) {

                    ArrayList<String> orderDetailUuidslist = new ArrayList<>();
                    if (orderDetailUuidslist.size() > 0) {
                        orderDetailUuidslist.clear();
                    }
                    orderDetailUuidslist.add(datalist.get(position).uuid);

                    Intent intent = new Intent(mContext, SelectPeopleActivity.class);
                    intent.putExtra("select_style", SelectPeopleActivity.SELECT_SIGNAL);
                    intent.putExtra("unSelectNum", 1);
                    intent.putExtra("orderMainUuid", orderMainUuid);
                    intent.putStringArrayListExtra("orderDetailUuidslist", orderDetailUuidslist);
                    mContext.startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.btn_next)
    public void onViewClicked() {
        // 完成选房，未选择的房间数为0， 去支付
//        if (unSelectNum == 0) {
//            // 预订单支付，
//            toOrderPay();
//        } else if (unSelectNum > 0) {
//            ToastUtil.showToast("还有未选择的房间，请选择");
//        } else if (unSelectNum < 0) {
//            ToastUtil.showToast("获取房态失败，请重新刷新获取");
//        }


//        Intent intent = new Intent(mContext, ConfirmOrderActivity.class);
//        intent.putExtra("mainUuid",orderMainUuid);
//        intent.putExtra("detailUuid",orderDetailUuid);
//        intent.putExtra("bean",datalist);
//        mContext.startActivity(intent);

        // TODO: 2017/12/4 去确认入住单页面
        // 完成选房，选房个数大于1， 去支付
        if (selectNum > 0) {
            // 预订单支付，
            // TODO: 2017/12/5 这里增加一个流程，宾客入住单
            Intent intent = new Intent(mContext, ConfirmOrderActivity.class);
            intent.putExtra("mainUuid",orderMainUuid);
            intent.putExtra("detailUuid",orderDetailUuid);
            intent.putExtra("bean",datalist);
            intent.putExtra("name",getIntent().getStringExtra("name"));

            mContext.startActivity(intent);

            //toOrderPay();
        }else if (selectNum <= 0) {
            ToastUtil.showToast("请选择入住人");
        }
    }

    private void toOrderPay() {
        LogUtil.e("xyd", "开始进行预订单支付");
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("orderUuid", orderMainUuid);                 // 预订单主表uuid
        h1.put("orderDetailUuid", orderDetailUuid);         // 预订单明细uuid

        Call<HttpResult<OrderBean>> call = service.toOrderPay(JsonUtils.convertParam("toOrderPay", h1));
        call.enqueue(new CallbackImpl<OrderBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<OrderBean>> call, Response<HttpResult<OrderBean>> response) {

                OrderBean prepayBean = response.body().getData();


                SharePrefUtil.saveString(mContext, ShareKeys.payOrderId, prepayBean.payOrderId);

                Intent intent = new Intent(mContext, PayPledgeActivity.class);
                intent.putExtra("fromPage", PayPledgeActivity.PayCheckIn);
                intent.putExtra("prepaybean", prepayBean);
                mContext.startActivity(intent);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        if (EventBusKeys.hadPayCheckIn.equals(event)) {
            finish();
        }

        if (EventBusKeys.refreshSelfSelect.equals(event)){
            toChooseRoom();
        }
    }

}
